package chances.epg.commons.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

public class URLUtils {
	/**
	 * 链接上加参数.
	 * 
	 * @param url
	 * @param name
	 * @param value
	 * @return
	 */
	public static String appendParam(String url, String name, Object value) {
		if (url.indexOf("?") > 0) {
			String currUrl = StringUtils.substringBefore(url, "?");
			String queryString = StringUtils.substringAfter(url, "?");
			queryString = addParam(queryString, name + "=" + value);
			return currUrl + "?" + queryString;
		} else {
			return url + "?" + name + "=" + value;
		}
	}

	/**
	 * 
	 * @param url
	 * @param queryString
	 * @return
	 */
	public static String appendQueryString(String url, String queryString) {
		if (url == null || url.length() == 0) {
			return url;
		}

		if (queryString == null || queryString.length() == 0) {
			return url;
		}

		String result = url;
		if (url.indexOf("?") != -1) {
			result += "&";
		} else {
			result += "?";
		}

		result += queryString;
		return result;
	}

	public static String divParams(String queryString, String paramName) throws UnsupportedEncodingException {
		if (StringUtils.isBlank(queryString))
			return "";
		if (StringUtils.isBlank(paramName))
			return queryString;
		String[] paramValues = queryString.split("&");
		String[] keyValues;
		String value = "";
		StringBuffer sb = new StringBuffer();
		for (String paramValue : paramValues) {
			keyValues = paramValue.split("=");
			if (keyValues.length == 0)
				continue;
			if (!paramName.equals(keyValues[0])) {
				if (keyValues.length == 2) {
					value = keyValues[1];
				} else {
					value = "";
				}
				sb.append(keyValues[0]).append("=").append(URLEncoder.encode(value, "UTF-8")).append("&");
			}
		}

		if (sb.toString().endsWith("&")) {
			return sb.substring(0, sb.length() - 1);
		}
		if (StringUtils.isBlank(sb.toString())) {
			return "";
		}
		return queryString;
	}

	public static String divFullUrlParams(String url, String paramName) throws UnsupportedEncodingException {
		if (url.indexOf("?") == -1)
			return url;
		String queryString = url.substring(url.indexOf("?") + 1);
		return url.substring(0, url.indexOf("?") + 1) + divParams(queryString, paramName);
	}

	public static String removeParams(String queryString, String paramName) {
		if (null == queryString) {
			return null;
		}
		Pattern pattern = Pattern.compile(paramName + "=\\w*");
		String param = "";
		if (StringUtils.isNotEmpty(queryString)) {
			Matcher matcher = pattern.matcher(queryString);
			if (matcher.find()) {
				queryString = matcher.replaceAll(param);
			}
		}
		if (queryString.endsWith("&")) {
			queryString = queryString.substring(0, queryString.length() - 1);
		}
		if (queryString.startsWith("&")) {
			queryString = queryString.substring(1, queryString.length());
		}
		queryString = queryString.replace("&&", "&");
		return queryString;
	}

	public static String getCurrentPath(HttpServletRequest request, String host, String params, String excludeParams) {

		String queryString = request.getQueryString();
		if (queryString == null) {
			queryString = "";
		}
		if (params != null) {
			queryString = URLUtils.addParam(queryString, params);
		}
		if (excludeParams != null) {
			String[] eParams = excludeParams.split(",");
			Map<String, String> paramMap = extectMap(queryString);
			for (String key : eParams) {
				paramMap.remove(key);
			}
			queryString = toQueryString(paramMap);
		}

		String aPrams = queryString.length() > 0 ? "?" + queryString : "";
		String servletPath = getCurrentPath(request);
		String result = PathUtils.join(host, servletPath) + aPrams;
		return result;
	}

	/**
	 * 鍦≦ueryString涓坊鍔犲弬鏁帮紝浼氬墧闄ら噸澶嶇殑鍙傛暟
	 * 
	 * @param queryString
	 * @param addParams
	 * @return
	 */
	public static String addParam(String queryString, String addParams) {
		if (StringUtils.isEmpty(queryString)) {
			return addParams;
		}
		Map<String, String> oldParams = extectMap(queryString);
		Map<String, String> newParams = extectMap(addParams);
		oldParams.putAll(newParams);
		return toQueryString(oldParams);
	}

	/**
	 * 灏哘ueryString 杞崲涓篗ap<String,String>瀵硅薄
	 * 
	 * @param queryString
	 * @return
	 */
	public static Map<String, String> extectMap(String queryString) {

		String key = "";
		String value = "";
		Map<String, String> result = new HashMap<String, String>();
		String[] keyValues = queryString.split("&");
		for (int i = 0; i < keyValues.length; i++) {
			String keyVal = keyValues[i];
			if (keyVal.indexOf("=") != -1) {
				key = keyVal.substring(0, keyVal.indexOf("="));
				value = keyVal.substring(keyVal.indexOf("=") + 1);
				result.put(key, value);
			}
		}
		return result;
	}

	/**
	 * 鐢熸垚QueryString
	 * 
	 * @param oldParams
	 *            鍙傛暟
	 * @return queryString
	 */
	public static String toQueryString(Map<String, String> oldParams) {
		StringBuffer buffer = new StringBuffer();
		Set<Entry<String, String>> paramSet = oldParams.entrySet();
		for (Iterator<Entry<String, String>> iter = paramSet.iterator(); iter.hasNext();) {
			Entry<String, String> entry = iter.next();
			buffer.append(entry.getKey()).append("=").append(entry.getValue());
			if (iter.hasNext()) {
				buffer.append("&");
			}

		}
		return buffer.toString();
	}

	public static String getCurrentPath(HttpServletRequest request) {
		String servletPath = (String) request.getAttribute("javax.servlet.forward.request_uri");
		if (servletPath == null) {
			servletPath = PathUtils.join(request.getContextPath(), request.getServletPath());
		} else {
			servletPath =  StringUtils.substringBefore(servletPath, "?");
		}

		return servletPath;
	}

}
